package org.dreamwork.tools.simulator.connector.web;

import org.dreamwork.tools.simulator.connector.managed.LocalConfig;
import org.dreamwork.concurrent.Looper;
import org.dreamwork.injection.IObjectContext;
import org.dreamwork.injection.ObjectContextFactory;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class InitListener implements ServletContextListener {
    @Override
    public void contextInitialized (ServletContextEvent event) {
        ServletContext app = event.getServletContext ();
        try {
            IObjectContext context = ObjectContextFactory.start (LocalConfig.class, "--without-logs");
            app.setAttribute (IObjectContext.class.getCanonicalName (), context);
        } catch (Exception ex) {
            throw new RuntimeException (ex);
        }
    }

    @Override
    public void contextDestroyed (ServletContextEvent event) {
        ServletContext app = event.getServletContext ();
        IObjectContext ctx = (IObjectContext) app.getAttribute (IObjectContext.class.getCanonicalName ());
        if (ctx != null) {
            try {
                ctx.dispose ();
            } catch (Throwable ex) {
                ex.printStackTrace ();
            }
        }

        Looper.exit ();

        System.err.println ("inject context disposed.");
        System.err.println ("looper exited.");
    }
}